package com.kobeliu.controller;


import com.google.gson.Gson;
import com.kobeliu.api.interceptor.JwtCurrentUserInterceptor;
import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.pojo.Admin;
import com.kobeliu.pojo.Users;
import com.kobeliu.pojo.bo.AdminBO;
import com.kobeliu.pojo.bo.RegistryLoginBO;
import com.kobeliu.pojo.vo.AdminVO;
import com.kobeliu.pojo.vo.UsersVO;
import com.kobeliu.result.GraceJSONResult;
import com.kobeliu.result.ResponseStatusEnum;
import com.kobeliu.result.SMSSendResult;
import com.kobeliu.service.AdminService;
import com.kobeliu.service.UsersService;
import com.kobeliu.utils.IPUtil;
import com.kobeliu.utils.JwtUtils;
import com.kobeliu.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@Slf4j
@RequestMapping("/admin")
public class AdminController extends BaseInfoProperties {

    @Autowired
    private SMSUtils smsUtils;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AdminService adminService;

    @RequestMapping(method = RequestMethod.POST,path = "login")
    public GraceJSONResult login(@Valid @RequestBody AdminBO adminBO, HttpServletRequest request){

       if(!adminService.adminLogin(adminBO)){
           return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
       }

       //获得admin信息
        AdminVO adminVO = adminService.getAdminVO(adminBO);
       if(adminVO==null) {
           return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIST);
       }

       //做jwtToken穿给前端进行校验
        String jwtToken = jwtUtils.createJwtWithPrefix(new Gson().toJson(adminVO),TOKEN_ADMIN_PREFIX);

       return GraceJSONResult.ok(jwtToken);
    }

    @RequestMapping(method = RequestMethod.GET,path = "info")
    public GraceJSONResult login(){

        //token的解析包含在headers中，在interceptor时已经进行了转化
        //所以我们只需要去threadlocal中去拿就可以
        Admin currentAdmin = JwtCurrentUserInterceptor.currentAdmin.get();

        if(currentAdmin!=null){
            AdminVO adminVO = new AdminVO();
            BeanUtils.copyProperties(currentAdmin,adminVO);
            return GraceJSONResult.ok(adminVO);
        }

        return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIST);
    }
}
